<template>
  <div class="table-wrapper">
    <el-table :data="data" stripe style="width: 100%" size="mini" header-row-class-name="inClass" :row-class-name="tableRowClassName" v-bind="$attrs" v-on="$listeners">
      <el-table-column v-for="(column, index) in mergeColumns" :key="index" v-bind="mergeColumns[index]">
        <template v-if="column.slotName" v-slot="slotProps">
          <slot :name="column.slotName" :row="slotProps.row" :column="column"></slot>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import Dayjs from 'dayjs'
const COMPONENT_NAME = 'guodeTable'
export default {
  name: COMPONENT_NAME,
  props: {
    data: Array,
    columnDefault: {
      type: Object,
    },
    columns: Array,
  },
  computed: {
    mergeColumns() {
      return this.columns.map((column) => {
        Utils.handleFormatter(column)
        return Object.assign(column, this.columnDefault)
      })
    },
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      return rowIndex % 2 === 0 ? '' : 'warning-row'
    },
  },
}

class Utils {
  static isString(value) {
    return toString.call(value)
  }

  static handleFormatter(column) {
    // 处理 formatter 定制规则
    if (column.hasOwnProperty('formatter') && Utils.isString(column.formatter)) {
      let formatValue = 'YYYY-MM-DD HH:mm:ss'
      const value = column.formatter

      //日期处理: day | day('YYYY-MM')
      if (/^day/.test(value)) {
        // day("HH:mm:ss") => HH:mm:ss
        value.match(/\((\S+)\)/)
        const argumentsStr = RegExp.$1
        if (argumentsStr) {
          formatValue = argumentsStr.split(',')[0].replaceAll('"', '')
        }
        column.formatter = (row, column, cellValue, index) => Dayjs(cellValue).format(formatValue)
      }
    }
  }
}
</script>

<style lang="scss">
.table-wrapper {
  .inClass {
    th.el-table__cell {
      font-size: $size-text-mini;
      // color: $color-text-white;
      // color: $color-text-white;
      // background-color: $color-main;
      background-color: #d3e7ff;
      color: #333;
    }
  }
  tr.el-table__row--striped.warning-row td.el-table__cell {
    background: #f4faff;
  }
  .el-table tbody tr:hover > td {
    background: #e7f4ff !important;
  }
  .el-table::before {
    height: 0px;
  }
  .el-table td {
    font-size: 14px;
    color: #2d2d2d;
    font-family: Source Han Sans CN Normal, Source Han Sans CN Normal-Normal;
  }
  .el-table__expanded-cell {
    padding: 0;
  }
}
</style>